// vuex 频道管理模块
import { getChannels, getAllChannels } from '@/api/channels'

const state = {
  channels: [], // 用户频道
  allChannels: [], // 所有频道
}
const mutations = {
  // 设置用户频道
  setChannels(state, channels) {
    state.channels = channels
  },

  // 设置所有频道
  setAllChannels(state, allChannels) {
    state.allChannels = allChannels
  },

  // 添加频道
  addChannel(state, channel) {
    state.channels.push(channel)
  },

  // 删除频道
  delChannel(state, channel) {
    state.channels = state.channels.filter(item => item.id !== channel.id)
  },
}
const actions = {
  // 获取用户频道
  async getChannelsAsync(context) {
    const { data } = await getChannels()
    context.commit('setChannels', data.data.channels)
  },

  // 获取所有频道
  async getAllChannelsAsync(context) {
    const { data } = await getAllChannels()
    context.commit('setAllChannels', data.data.channels)
  },
}
const getters = {
  // 获取可选频道
  optionChannels(state) {
    // 过滤出与用户频道不同的所有频道
    return state.allChannels.filter(
      item => !state.channels.some(value => item.id === value.id)
    )
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}
